#include "Application.h"
#include "mmsystem.h"
#include "Window.h"
#include "GameManager.h"
#include "Network/Network.h"
#include "GameManager.h"
#include "Login/LoginManager.h"

HINSTANCE Application::ghInstance = NULL;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

Application::Application()
:mWidth(0),
mHeight(0),
mbActive(false)
{
}

Application::~Application()
{
}

void Application::loadConfig()
{
	mWidth = 800;
	mHeight = 600;
	mName = "Gobang";
}

void Application::initSystemElements()
{
	addSysElement(GameManager::getSingletonPtr());
	addSysElement(Network::getSingletonPtr());
	addSysElement(LoginManager::getSingletonPtr());
	
	for(SystemElementList::iterator it = mSysElementList.begin();
		it != mSysElementList.end(); ++it)
	{
		(*it)->init();
	}
}

void Application::init()
{
	loadConfig();
	new Window(200, 200, mWidth, mHeight, mName.c_str());
	initMainWindow();
	initSystemElements();
}

void Application::initScene()
{

}

void Application::initMainWindow()
{
	Window::getMainWindow()->RegisterWindowClass();
	Window::getMainWindow()->InitInstance();
}

void Application::doFrame(double deltaTime)
{
}

void Application::doIdleFrame(double deltaTime)
{
}

DWORD Application::run()
{
	GameManager::getSingletonPtr()->login();

	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	double lastTime = timeGetTime();

	while (msg.message != WM_QUIT)
	{
		while (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		
		double currTime = timeGetTime();
		double deltaTime = (currTime - lastTime) * 0.001f;

		if(deltaTime > 0.05f)
			deltaTime = 0.05f;

		if(deltaTime > 0.03f)
		{
			if(mbActive)
				doFrame(deltaTime);
			else
				doIdleFrame(deltaTime);
		}
		else
			Sleep(5);

		lastTime = currTime;
	}

	return msg.wParam;
}

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow)
{
	Application::ghInstance = hInstance;
	Application *pApp = Application::getSingletonPtr();
	
	pApp->init();
	pApp->initScene();
	pApp->run();
}